// pages/keepLight/keepLight.js
var app = getApp()
var url = app.url
var header = {
  'content-type': 'application/x-www-form-urlencoded',
  'cookie': "openid=" + app.globalData.openid
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showLoading: true, // 等待动画
    fzList: [],
    keepSheetHidden: true,
    keepSheetItems: [
      { bindtap: 'Menu1', txt: '全开' },
      { bindtap: 'Menu2', txt: '全关' },
      { bindtap: 'Menu3', txt: '取消' },
    ],
    menu: '',
    //chidx: 0,// 选中地区下标
    chmid:"", // 选中地区的mid 现在用的
    //opType: '',// 1==开，0==关
    cur_district_allbranch:{},
    all_district_allbranch:{},
    cur_district:"",
    branchdevNoliststr:""  //用来closeall 或者openall的devno逗号隔开的字符串
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //var name = wx.getStorageSync('userName')
    let name = app.globalData.login_name;
    // console.log(name, "name");
    // console.log(app.globalData.userid);
    
    this.getUserMeters()
    // if (name == '' || name == null) {
    //   wx.showModal({
    //     title: '提示',
    //     content: "用户未登录",
    //     confirmText: '去登录',
    //     showCancel: false,
    //     success: function () {
    //       wx.redirectTo({
    //         url: '../login/login',
    //       })
    //     }
    //   })
    // } else {
    //   this.getUserMeters()
    // }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //this.setData({ fzList: [], keepSheetHidden: true, showLoading: true })
    //this.getUserMeters()
  },

  checkLogin: function () {
    //var name = wx.getStorageSync('userName')
    let name = app.globalData.login_name;

    if (name == '' || name == null) {
      wx.showModal({
        title: '提示',
        content: "用户未登录",
        confirmText: '去登录',
        showCancel: false,
        success: function () {
          wx.navigateTo({
            url: '../login/login',
          })
        }
      })
    }
  },
  actionSheetTap: function (e) {
    // var idx = e.currentTarget.dataset.idx
    // this.setData({
    //   chidx: idx, keepSheetHidden: !this.data.keepSheetHidden
    // })

    let mid = e.currentTarget.dataset.mid
    let cur_district = e.currentTarget.dataset.district
    this.setData({
      chmid: mid, 
      keepSheetHidden: !this.data.keepSheetHidden,
      cur_district:cur_district
    })
  },
  keepSheetChange: function () {
    this.setData({
      keepSheetHidden: !this.data.keepSheetHidden
    })
  },
  //全开
  bindMenu1: function () {
    this.setData({
      menu: 1, opType: 1, 
      keepSheetHidden: !this.data.keepSheetHidden
    })
    this.lightSubmit()
  },
  //全关
  bindMenu2: function () {
    this.setData({
      menu: 2, opType: 0, 
      keepSheetHidden: !this.data.keepSheetHidden
    })
    this.lightSubmit()
  },
  //取消
  bindMenu3: function () {
    this.setData({
      menu: 3, opType: '',
      keepSheetHidden: !this.data.keepSheetHidden
    })
  },
  getUserMeters: function () {
    var that = this
    // var header = { 'content-type': 'application/x-www-form-urlencoded' }
    // var params = { userName: wx.getStorageSync('userName') }    
    // var encodingStr = app.ecbEncrypto(params)
    //http://119.3.130.227/server/loadTree?userid=922aeb81-29c8-41ba-9f82-36d9abb33265
    wx.request({
      url: app.globalData.url + 'loadTree',
      data:{
        userid:app.globalData.userid
      },
      method: 'POST',
      header: header,
      success: function (res) {
        //console.log(res, "res");
        let  data = JSON.parse(res.data.data)

        if (data.length != 0) {
          //这边数据需要重新组织 [{"attributes":{"mid":1,"type":0},"id":100000001,"text":"测试区域2","state":"closed","iconCls":"area_img"},{"attributes":{"mid":44,"type":0},"id":100000044,"text":"沛县","state":"closed","iconCls":"area_img"},{"attributes":{"mid":45,"type":0},"id":100000045,"text":"测试","state":"closed","iconCls":"area_img"},{"attributes":{"mid":46,"type":0},"id":100000046,"t...}]
         that.optionList(data)
        } else if(res.errMsg != "request:ok"){
          wx.showModal({
            title: '提示',
            content: res.errMsg,
            showCancel: false
          })
        }
      },
      complete: function () {
        wx.stopPullDownRefresh()
        that.setData({ showLoading: false })
      }
    })
  },
  // 操作数据分组
  optionList: function (list) {
    var arr = {}
    // if(list.length > 0){
    //   for(var i = 0; i < list.length; i++){
    //     var st = list[i][0].SWITCH_STATUS
    //     var result = ['--', '--', '--', '--'];
    //     if (st != '' && st != undefined){      
    //       var sp= st.split('|');
    //       for(var j=0;j<sp.length;j++){
    //         result[j] = sp[j];
    //       }
    //     }
    //     list[i][0].SWITCH_STATUS = result;
    //     if (arr[list[i][0].DEPTNAME]){
    //       arr[list[i][0].DEPTNAME].push(list[i][0])
    //     }else{
    //       var lr = new Array()
    //       lr.push(list[i][0])
    //       arr[list[i][0].DEPTNAME] = lr
    //     }
    //   }
    // }
    // var objs = []
    // for (i in arr) {
    //   var ob = { name: i, array: arr[i]}
    //   objs.push(ob)
    // }

       //这边数据需要重新组织 [{"attributes":{"mid":1,"type":0},"id":100000001,"text":"测试区域2","state":"closed","iconCls":"area_img"},{"attributes":{"mid":44,"type":0},"id":100000044,"text":"沛县","state":"closed","iconCls":"area_img"},{"attributes":{"mid":45,"type":0},"id":100000045,"text":"测试","state":"closed","iconCls":"area_img"},{"attributes":{"mid":46,"type":0},"id":100000046,"t...}]
    
    var objs = []
    if(list.length > 0){      
      list.forEach(element => {
        let tmp_arr = {}
        tmp_arr.name = element.text
        tmp_arr.mid = element.attributes.mid
        objs.push(tmp_arr)        
      });
      this.setData({ fzList: objs })
    }    
  },
  // 跳转
  showZdByName: function (e) {
    var idx = e.currentTarget.dataset.idx    
    let mid = e.currentTarget.dataset.mid
    let district  = e.currentTarget.dataset.district
    //var list = this.data.fzList
    //wx.setStorageSync("area" + idx, list[idx])// 缓存数据
    wx.navigateTo({
      url: '../area/area?mid='+mid+'&district='+district
    })
  },
  // 控制路灯事件
  lightSubmit: function () {
    var that = this
    var idx = that.data.chidx
    var mid = that.data.chmid
    // var list = that.data.fzList
    // var array = list[idx].array
    // var nos = ''
    // var msg = ""
    let menuType = that.data.menu
    wx.showLoading({
      title: '提交中',
    })

    //FindAllBranchDeviceInDepartment
    wx.request({
      url: app.globalData.url+'FindAllBranchDeviceInDepartment',
      type:"post",
      header:header,
      data:{
        departmentID:mid
      },
      success:res=>{
          //一个分支的输出{"result":"{\"0025015F\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"沛龙大道（三里村）\",\"gname\":\"沛龙大道(三里村)\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"002502AA\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"经四路北段\",\"gname\":\"经四路北段\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false}]},\"0025015E\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"沛龙大道西段\",\"gname\":\"沛龙大道西段\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"0025015C\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"龙固大堤\",\"gname\":\"龙固大堤\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"0025015A\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"四海停车场\",\"gname\":\"四海停车场\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"0025016B\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"沛龙大道（龙固小加油站）\",\"gname\":\"沛龙大道（龙固小加油站）\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"00250160\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"龙固镇委\",\"gname\":\"龙固镇委\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"002502A9\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"经四路南段\",\"gname\":\"经四路南段\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false}]},\"002502A4\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"龙固工业区\",\"gname\":\"龙固工业区\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]}}"}

        //另一个分支测试区域2的输出 {"result":"{\"002501B1\":{\"autoUnusual\":0,\"online\":false,\"dname\":\"本地测试\",\"gname\":\"测试路段\",\"branch\":[{\"port\":\"1\",\"switch\":false},{\"port\":\"0\",\"switch\":true}]}}"} 
        
        let res_json = res.data.result    
        let result = JSON.parse(res_json)
        //console.log(result, "result")   
        let devNoStrArr = []
        let devNoStr = ""
        if(result != {}){
          //取消按钮 无需组织设备号
          if(menuType !== 3){
            for (var val in result) {
              //全开按钮 一看设备是否在线 二看设备 是否开着 
              //console.log(result[val].online, "online")
                     
              if(result[val].online === true){
                devNoStrArr.push(val); //val 就是 \"002502A9\" 这些
              } 
            }
          }        
        }

        if(devNoStrArr.length != 0){
          devNoStr = devNoStrArr.join(",")
        }
       
        //console.log(devNoStr, "devNoStr");

        //console.log(menuType, "menuType")
        // console.log(typeof(menuType), "typeof menuType")

        if(menuType === 1){
          if(devNoStr != ""){
            wx.request({
              header:header,
              url: app.globalData.url+"OpenBranchAll",
              type:"post",
              data:{
                devNoList:devNoStr
              },
              success:res=>{
                wx.hideLoading()
                //console.log(res.data.error == 0, "res.data.error == 0")
                if(res.data.error == 0){
                  wx.showToast({
                    title: '全开操作成功',
                    icon: 'success',
                    duration: 2000
                  })
                }
                if(res.data.error == -1){
                  wx.showToast({
                    title: '全开操作失败',
                    icon: 'error',
                    duration: 2000
                  })
                }                
              }
            })
          }
        }

        if(menuType === 2){
          if(devNoStr != ""){
            wx.request({
              header:header,
              url: app.globalData.url+"CloseBranchAll",
              data:{
                devNoList:devNoStr
              },
              success:res=>{
                wx.hideLoading()
                //console.log(res.data.error == 0, "res.data.error == 0")
                if(res.data.error == 0){
                  wx.showToast({
                    title: '全关操作成功',
                    icon: 'success',
                    duration: 2000
                  })
                }
                if(res.data.error == -1){
                  wx.showToast({
                    title: '全关操作失败',
                    icon: 'error',
                    duration: 2000
                  })
                }
              }
            })
          }          
        }

        if(menuType === 3){
          
        }
      }
    })

   

    // for(var i = 0;i < array.length; i++){
    //   if (array[i].IS_ONLINE == 1){
    //     nos = array[i].TERMINAL_ADDRESS
    //     var flag = true
    //     var header = { 'content-type': 'application/x-www-form-urlencoded' }
    //     var params = {
    //       userName: wx.getStorageSync('userName'), meterAddr: nos, operationId: that.data.opType, branch: 1
    //     }
    //     var encodingStr = app.ecbEncrypto(params)
    //     wx.request({
    //       url: url + '/xywl/pullSwitchMeter.htm',
    //       data: encodingStr,
    //       method: 'POST',
    //       header: header,
    //       success: function (res) {
    //         var decodingStr = app.ecbDecrypto(res.data)
    //         var rest = JSON.parse(decodingStr)
    //         if (rest.res == 0) {
    //           var respone = rest.respone
    //           if (respone.strBackFlag == 1) {
               
    //           } else {
    //             msg = "设置失败，请重试！"
    //             flag = false
    //           }

    //         } else {
    //           that.data.msg = rest.errorMsg
    //           flag = false
    //         }
    //       }
    //     })
    //     if (!flag) {
    //       break
    //     }
    //   }
    // }
   
    // if (!flag) {
    //   wx.showModal({
    //     title: '提示',
    //     content: that.data.msg,
    //     showCancel: false
    //   })
    // } else {
    //   wx.showModal({
    //     title: '提示',
    //     content: '设置成功！',
    //     showCancel: false
    //   })
    // }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})